package indi.mozping.bio;

import indi.mozping.utils.Utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * @author by mozping
 * @Classname BioClient
 * @Description BIO 客户端
 * 客户端可以从控制台读取消息，发送给服务端
 * 如果发送over，服务端就会断开连接
 * @Date 2019/4/22 12:43
 */
public class BioClient {

    private static final int PORT = Utils.PORT;
    private static final String IP = Utils.IP;
    static PrintWriter printWriter = null;

    public static void main(String[] args) throws IOException {
        Socket socket = new Socket(IP, PORT);
        System.out.println("Input your info:");
        //新启动一个写线程用于发送消息到服务端
        //新启动一个读线程用于接收服务端的响应消息
        new WriteThread(socket).start();
        new ReadThread(socket).start();
    }

    static class WriteThread extends Thread {
        static Socket socket;

        WriteThread(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try {
                PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
                String line;
                while (true) {
                    line = new Scanner(System.in).next();
                    printWriter.println(line);
                    if ("over".equalsIgnoreCase(line)) {
                        break;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                System.out.println("write thread end ...");
            }
        }
    }

    static class ReadThread extends Thread {
        static Socket socket;

        ReadThread(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String line = null;
                while (true) {
                    while ((line = bufferedReader.readLine()) != null) {
                        if ("over".equalsIgnoreCase(line)) {
                            return;
                        }
                        System.out.printf("收到数据: %s", line);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                System.out.println("read thread end ...");
                clear(socket);
            }
        }

    }

    private static void clear(Socket socket) {
        if (socket != null) {
            try {
                System.out.println("client close...");
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
